/*******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/
package com.google.gwt.sample.stockwatcher.server;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gwt.dev.util.collect.HashMap;

/**
 * This servlet gets colors that match the query string. It can be accessed as
 * GET /multivaluesuggestboxexample/colors. The colors are from
 * http://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
 */
public class CrayonColorsServlet extends HttpServlet
{
    private static final long serialVersionUID = -5188855294730126999L;
    //private static final ArrayList<String> g_colorCodes;
    private static final HashMap<String, String> g_colorCodes;
    
    private String m_lastQuery;
    private JSONArray m_lastResults;
    
    //read from the text file and parse into Symbol and Name pairs
    
    
    static {
    	g_colorCodes = fetchStockSymbolList();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException,
            IOException
    {
        JSONArray fullColorArray;
        String query = request.getParameter("q");
        
        int count = 0;
        if (query.equals(m_lastQuery)) {
            fullColorArray = m_lastResults;
            count = m_lastResults.length();
        } else {
            m_lastQuery = query;
            
            fullColorArray = new JSONArray();
            for (String colorCode : g_colorCodes.values()) {
                String colorName = colorCode;
               // String lowerColor = colorName.toLowerCase();
                int has = colorName.indexOf(query);
                
                if (!query.isEmpty() && (query.equals("*") || has >= 0)) {
                    JSONObject color = new JSONObject();
                    color.put("DisplayName", colorName);
                    //color.put("Value", colorCode[1]);
                    fullColorArray.put(color);
                    count++;
                }
            }
            m_lastResults = fullColorArray;
        }
        
        //get the partial array to be returned
        int indexFrom = Integer.parseInt(request.getParameter("indexFrom"));
        int indexTo = Integer.parseInt(request.getParameter("indexTo"));
        
        JSONArray partial = new JSONArray();
        if (fullColorArray.length() > 0) {
            int end = count - 1 > indexTo ? indexTo : count - 1;
            for (int i = indexFrom; i <= end; i++) {
                partial.put(fullColorArray.get(i));
            }
        }        
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        
        JSONObject obj = new JSONObject();
        obj.put("TotalSize", count);
        obj.put("Options", partial);
        out.println(obj.toString());
    }
    
    private static HashMap<String, String> fetchStockSymbolList(){

		
		//ArrayList<String> stockSymbolList = new ArrayList<String>();
		HashMap<String, String> fileCache = new HashMap<String, String>();
		try {
			FileReader stockFileReader = new FileReader("war/input/NASDAQ.txt");
			BufferedReader br = new BufferedReader(stockFileReader);
			br.readLine();
			while(br.ready()){
				String currentSymbol = br.readLine();
				String symbol = currentSymbol.substring(0, 5);
				String text = currentSymbol.substring(6);
				fileCache.put(symbol, text);
			//stockSymbolList.add(br.readLine());
			}	
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//return stockSymbolList;
		return fileCache;
	
    }
}
